package com.neusoft.elmboot.mapper;

import com.neusoft.elmboot.po.UserCoupon;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserCouponMapper {
	
	/**
	 * 插入用户优惠券
	 */
	@Insert("INSERT INTO user_coupons (userId, itemId, couponCode, couponName, discountAmount, minimumAmount, expiryDate, status) " +
			"VALUES (#{userId}, #{itemId}, #{couponCode}, #{couponName}, #{discountAmount}, #{minimumAmount}, #{expiryDate}, 1)")
	@Options(useGeneratedKeys = true, keyProperty = "couponId")
	int insertCoupon(UserCoupon coupon);
	
	/**
	 * 根据couponId获取优惠券
	 */
	@Select("SELECT * FROM user_coupons WHERE couponId = #{couponId}")
	UserCoupon getCouponById(Integer couponId);
	
	/**
	 * 根据couponCode获取优惠券
	 */
	@Select("SELECT * FROM user_coupons WHERE couponCode = #{couponCode}")
	UserCoupon getCouponByCode(String couponCode);
	
	/**
	 * 获取用户未使用的优惠券列表
	 */
	@Select("SELECT * FROM user_coupons WHERE userId = #{userId} AND status = 1 AND expiryDate > NOW() ORDER BY expiryDate ASC")
	List<UserCoupon> getAvailableCouponsByUserId(String userId);
	
	/**
	 * 获取用户所有优惠券
	 */
	@Select("SELECT * FROM user_coupons WHERE userId = #{userId} ORDER BY createdTime DESC")
	List<UserCoupon> getCouponsByUserId(String userId);
	
	/**
	 * 使用优惠券
	 */
	@Update("UPDATE user_coupons SET status = 2, usedDate = NOW(), usedOrderId = #{usedOrderId} WHERE couponId = #{couponId}")
	int useCoupon(@Param("couponId") Integer couponId, @Param("usedOrderId") Integer usedOrderId);
	
	/**
	 * 更新优惠券状态
	 */
	@Update("UPDATE user_coupons SET status = #{status} WHERE couponId = #{couponId}")
	int updateCouponStatus(@Param("couponId") Integer couponId, @Param("status") Integer status);
	
	/**
	 * 检查优惠券是否过期并更新状态
	 */
	@Update("UPDATE user_coupons SET status = 3 WHERE status = 1 AND expiryDate <= NOW()")
	int updateExpiredCoupons();
}
